// 引入标准输入输出库
#include "stdio.h"
// 引入信号处理库
#include "signal.h"

// 如果是Windows平台，引入Windows API
#if defined(WIN32) || defined(WIN64)
#include "windows.h"
#endif

// 引入POSIX线程库
#include "pthread.h"

// 数学库
#include <math.h>
// 标准整数类型
#include <stdint.h>
// 格式化整数输出
#include <inttypes.h>
// 硬件类型定义
#include "hw_type.h"
// 华为云IoT初始化
#include "iota_init.h"
// 华为云IoT配置
#include "iota_cfg.h"

// 日志工具
#include "LogUtil.h"
// JSON工具
#include "JsonUtil.h"
// 字符串工具
#include "StringUtil.h"
// 华为云登录
#include "iota_login.h"
// 华为云数据传输
#include "iota_datatrans.h"
// 字符串操作
#include "string.h"
// cJSON库
#include "cJSON.h"
// 系统类型定义
#include "sys/types.h"
// Unix标准函数
#include "unistd.h"
// 华为云错误类型
#include "iota_error_type.h"
// 内存分配
#include <malloc.h>
// 套接字编程
#include <sys/socket.h>
// 网络地址
#include <netinet/in.h>
// IP地址转换
#include <arpa/inet.h>
// 线程库
#include <pthread.h>

// TCP服务器端口定义
#define TCP_SERVER_PORT 60000
// 缓冲区大小
#define BUFFER_SIZE 1024

// 全局接收缓冲区（用于数据拼接）
static char g_recv_buffer[4096];
// 当前接收数据长度
static size_t g_recv_len = 0;

// 停车场数据全局缓冲区
static char g_parking_buffer[4096];
// 停车场数据缓冲区长度
static size_t g_parking_buffer_len = 0;

// 全局变量保存客户端连接文件描述符
static int g_client_fd = -1;
// 客户端连接互斥锁，用于线程安全
static pthread_mutex_t client_fd_mutex = PTHREAD_MUTEX_INITIALIZER;

// TCP服务器文件描述符
static int tcp_server_fd = -1;
// TCP服务器运行状态标志
static volatile int tcp_running = 1;
// TCP服务器线程ID
static pthread_t tcp_server_thread;

/* 如果想使用系统日志，需要这样做：
 * #include "syslog.h"
 * #define _SYS_LOG
 */

// 工作路径
char *workPath = ".";
// 网关ID
char *gatewayId = NULL;

// 报警值
int alarmValue = 0;

// 华为云服务器IP
char *serverIp_ = "";
// 华为云服务器端口
int port_ = 8883;

// 用户名（设备ID）
char *username_ = "600a9852942d2302db444b53_12334353";
// 密码
char *password_ = "78b662105979a77dedcd8ad351c7563f";

// 断开连接标志
int disconnected_ = 0;

// 子设备ID
char *subDeviceId = "f6cd4bbb1a8ab53acbb595efd0e90199_ABC123456789";

// 休眠时间（毫秒）
int sleepTime = 5000;

// 跨平台休眠函数
void timeSleep(int ms)
{
#if defined(WIN32) || defined(WIN64)
    // Windows平台使用Sleep
    Sleep(ms);
#else
    // Unix平台使用usleep
    usleep(ms * 1000);
#endif
}

// 设置客户端连接
void set_client_connection(int client_fd)
{
    pthread_mutex_lock(&client_fd_mutex);
    g_client_fd = client_fd;
    pthread_mutex_unlock(&client_fd_mutex);
}

// 获取客户端连接
int get_client_connection()
{
    int fd;
    pthread_mutex_lock(&client_fd_mutex);
    fd = g_client_fd;
    pthread_mutex_unlock(&client_fd_mutex);
    return fd;
}

// 转发命令到GEC6818开发板
void forward_command_to_gec6818(const char *command_name, const char *action, const char *target, int value, const char *data_type, const char *requestId)
{
    // 获取客户端连接
    int client_fd = get_client_connection();

    if (client_fd < 0)
    {
        printfLog(EN_LOG_LEVEL_ERROR, "No client connection available to forward command\n");
        return;
    }

    // 构建华为云标准格式的命令JSON
    cJSON *command_json = cJSON_CreateObject();
    cJSON_AddStringToObject(command_json, "command_name", command_name);

    // 如果有requestId就添加，没有就不添加
    if (requestId && strlen(requestId) > 0)
    {
        cJSON_AddStringToObject(command_json, "request_id", requestId);
    }
    else
    {
        // 如果没有requestId，生成一个简单的
        char temp_request_id[32];
        snprintf(temp_request_id, sizeof(temp_request_id), "temp_%ld", time(NULL));
        cJSON_AddStringToObject(command_json, "request_id", temp_request_id);
    }

    // 创建参数对象（华为云标准格式）
    cJSON *paras = cJSON_CreateObject();

    // 根据命令类型设置不同的参数
    if (strcmp(command_name, "update_display_data") == 0)
    {
        if (data_type)
        {
            cJSON_AddStringToObject(paras, "data_type", data_type);
        }
        if (value != -1)
        {
            cJSON_AddNumberToObject(paras, "new_value", value);
        }
    }
    else if (strcmp(command_name, "led_control") == 0)
    {
        if (action)
        {
            cJSON_AddStringToObject(paras, "action", action);
        }
        if (target)
        {
            cJSON_AddStringToObject(paras, "target", target);
        }
        if (value != -1)
        {
            cJSON_AddNumberToObject(paras, "value", value);
        }
    }
    else if (strcmp(command_name, "buzzer_control") == 0)
    {
        if (action)
        {
            cJSON_AddStringToObject(paras, "action", action);
        }
        if (value != -1)
        {
            cJSON_AddNumberToObject(paras, "value", value);
        }
    }

    // 将参数对象添加到命令中
    cJSON_AddItemToObject(command_json, "paras", paras);
    cJSON_AddNumberToObject(command_json, "timestamp", time(NULL));

    // 将JSON对象转换为字符串
    char *command_str = cJSON_PrintUnformatted(command_json);

    // 发送命令到开发板
    ssize_t ret = send(client_fd, command_str, strlen(command_str), 0);
    if (ret > 0)
    {
        printfLog(EN_LOG_LEVEL_INFO, "Command forwarded to GEC6818: %s\n", command_str);
    }
    else
    {
        printfLog(EN_LOG_LEVEL_ERROR, "Failed to forward command to GEC6818\n");
    }

    // 清理JSON对象
    cJSON_Delete(command_json);
    free(command_str);
}

// 检查是否是命令响应
int is_command_response(const char *data)
{
    cJSON *root = cJSON_Parse(data);
    if (!root)
        return 0;

    cJSON *type = cJSON_GetObjectItem(root, "type");
    int is_response = (type && cJSON_IsString(type) && strcmp(type->valuestring, "command_response") == 0);

    cJSON_Delete(root);
    return is_response;
}

// 处理命令响应
void handle_command_response(const char *response_data)
{
    cJSON *root = cJSON_Parse(response_data);
    if (!root)
    {
        printfLog(EN_LOG_LEVEL_ERROR, "Failed to parse command response\n");
        return;
    }

    // 从响应中提取信息
    char *request_id = JSON_GetStringFromObject(root, "request_id", NULL);
    char *status = JSON_GetStringFromObject(root, "status", NULL);
    char *message = JSON_GetStringFromObject(root, "message", NULL);

    printfLog(EN_LOG_LEVEL_INFO, "Command response - request_id: %s, status: %s, message: %s\n",
              request_id ? request_id : "NULL",
              status ? status : "NULL",
              message ? message : "NULL");

    cJSON_Delete(root);
}

//------------------------------------------------------测试数据上报---------------------------------------------------------------------

// 测试消息上报
void Test_messageReport()
{
    int messageId = IOTA_MessageReport(NULL, "data123", "123", "hello");
    if (messageId != 0)
    {
        printfLog(EN_LOG_LEVEL_ERROR, "AgentLiteDemo: Test_messageReport() failed, messageId %d\n", messageId);
    }
}

// 测试属性上报
void Test_propertiesReport()
{
    int serviceNum = 1; // 要上报的service数量
    ST_IOTA_SERVICE_DATA_INFO services[serviceNum];

    // 创建属性JSON
    cJSON *root;
    root = cJSON_CreateObject();
    cJSON_AddNumberToObject(root, "alarm", 0);
    cJSON_AddNumberToObject(root, "smokeConcentration", (double)(rand() % 900 + 100) / 10);
    cJSON_AddNumberToObject(root, "temperature", (double)(rand() % 900 + 100) / 10);
    cJSON_AddNumberToObject(root, "humidity", rand() % 100);
    cJSON_AddNumberToObject(root, "beep", rand() % 200);

    char *payload;
    payload = cJSON_Print(root);
    cJSON_Delete(root);

    // 设置服务数据
    services[0].event_time = getEventTimeStamp(); // 如果event_time设置为NULL，将使用IoT平台的时间
    services[0].service_id = "smokeDetector";
    services[0].properties = payload;

    // 上报属性
    int messageId = IOTA_PropertiesReport(services, serviceNum);
    if (messageId != 0)
    {
        printfLog(EN_LOG_LEVEL_ERROR, "AgentLiteDemo: Test_batchPropertiesReport() failed, messageId %d\n", messageId);
    }
    free(payload);
}

// 测试批量属性上报
void Test_batchPropertiesReport()
{
    int deviceNum = 1;                           // 要上报的设备数量
    ST_IOTA_DEVICE_DATA_INFO devices[deviceNum]; // 存储每个设备要上报的结构体数组
    int serviceList[deviceNum];                  // 对应存储每个设备要上报的服务数量
    serviceList[0] = 2;                          // 设备一要上报2个服务

    // 设备1的服务1要上报的数据内容：使用json格式
    char *device1_service1 = "{\"Load\":\"1\",\"ImbA_strVal\":\"3\"}";
    // 设备1的服务2要上报的数据内容：使用json格式
    char *device1_service2 = "{\"PhV_phsA\":\"2\",\"PhV_phsB\":\"4\"}";

    // 设置设备1的数据
    devices[0].device_id = subDeviceId;
    devices[0].services[0].event_time = getEventTimeStamp();
    devices[0].services[0].service_id = "parameter";
    devices[0].services[0].properties = device1_service1;

    devices[0].services[1].event_time = getEventTimeStamp();
    devices[0].services[1].service_id = "analog";
    devices[0].services[1].properties = device1_service2;

    // 批量上报属性
    int messageId = IOTA_BatchPropertiesReport(devices, deviceNum, serviceList);
    if (messageId != 0)
    {
        printfLog(EN_LOG_LEVEL_ERROR, "AgentLiteDemo: Test_batchPropertiesReport() failed, messageId %d\n", messageId);
    }
}

// 测试命令响应
void Test_commandResponse(char *requestId)
{
    char *pcCommandRespense = "{\"cmdRsp\":\"success\"}"; // 测试响应

    int result_code = 0;
    char *response_name = NULL;

    int messageId = IOTA_CommandResponse(requestId, result_code, response_name, pcCommandRespense);
    if (messageId != 0)
    {
        printfLog(EN_LOG_LEVEL_ERROR, "AgentLiteDemo: Test_commandResponse() failed, messageId %d\n", messageId);
    }
}

// 测试属性设置响应
void Test_propSetResponse(char *requestId)
{
    int messageId = IOTA_PropertiesSetResponse(requestId, 0, "success");
    if (messageId != 0)
    {
        printfLog(EN_LOG_LEVEL_ERROR, "AgentLiteDemo: Test_propSetResponse() failed, messageId %d\n", messageId);
    }
}

// 测试属性获取响应
void Test_propGetResponse(char *requestId)
{
    int serviceNum = 2;
    ST_IOTA_SERVICE_DATA_INFO serviceProp[serviceNum];

    char *property = "{\"Load\":\"5\",\"ImbA_strVal\":\"6\"}";

    serviceProp[0].event_time = getEventTimeStamp();
    serviceProp[0].service_id = "parameter";
    serviceProp[0].properties = property;

    char *property2 = "{\"PhV_phsA\":\"2\",\"PhV_phsB\":\"4\"}";

    serviceProp[1].event_time = getEventTimeStamp();
    serviceProp[1].service_id = "analog";
    serviceProp[1].properties = property2;

    int messageId = IOTA_PropertiesGetResponse(requestId, serviceProp, serviceNum);
    if (messageId != 0)
    {
        printfLog(EN_LOG_LEVEL_ERROR, "AgentLiteDemo: Test_propGetResponse() failed, messageId %d\n", messageId);
    }
}

//--------------------------------------------------------------------------------------------------------------------------------------------------

// 认证成功回调函数
void handleAuthSuccess(void *context, int messageId, int code, char *message)
{
    printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handleConnectSuccess(), login success\n");
    disconnected_ = 0;
}

// 认证失败回调函数
void handleAuthFailure(void *context, int messageId, int code, char *message)
{
    printfLog(EN_LOG_LEVEL_ERROR, "AgentLiteDemo: handleConnectFailure() error, messageId %d, code %d, messsage %s\n", messageId, code, message);
    // 判断网络是否可用等，然后重新登录
    printfLog(EN_LOG_LEVEL_ERROR, "AgentLiteDemo: handleConnectFailure() login again\n");
    int ret = IOTA_Connect();
    if (ret != 0)
    {
        printfLog(EN_LOG_LEVEL_ERROR, "AgentLiteDemo: handleConnectionLost() error, login again failed, result %d\n", ret);
    }
}

// 连接丢失回调函数
void handleConnectionLost(void *context, int messageId, int code, char *message)
{
    printfLog(EN_LOG_LEVEL_WARNING, "AgentLiteDemo: handleConnectionLost() warning, messageId, code %d, messsage %s\n", messageId, code, message);
    // 判断网络是否可用等，然后重新登录
    int ret = IOTA_Connect();
    if (ret != 0)
    {
        printfLog(EN_LOG_LEVEL_ERROR, "AgentLiteDemo: handleConnectionLost() error, login again failed, result %d\n", ret);
    }
}

// 断开认证成功回调函数
void handleDisAuthSuccess(void *context, int messageId, int code, char *message)
{
    disconnected_ = 1;

    printf("AgentLiteDemo: handleLogoutSuccess, login again\n");
    printf("AgentLiteDemo: handleDisAuthSuccess(), messageId %d, code %d, messsage %s\n", messageId, code, message);
}

// 断开认证失败回调函数
void handleDisAuthFailure(void *context, int messageId, int code, char *message)
{
    printf("AgentLiteDemo: handleLogoutFailure, login again\n");
    int ret = IOTA_Connect();
    if (ret != 0)
    {
        printfLog(EN_LOG_LEVEL_ERROR, "AgentLiteDemo: handleConnectionLost() error, login again failed, result %d\n", ret);
    }
    printf("AgentLiteDemo: handleDisAuthFailure(), messageId %d, code %d, messsage %s\n", messageId, code, message);
}

// 订阅成功回调函数
void handleSubscribesuccess(void *context, int messageId, int code, char *message)
{
    printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handleSubscribesuccess() messageId %d\n", messageId);
}

// 订阅失败回调函数
void handleSubscribeFailure(void *context, int messageId, int code, char *message)
{
    printfLog(EN_LOG_LEVEL_WARNING, "AgentLiteDemo: handleSubscribeFailure() warning, messageId %d, code %d, messsage %s\n", messageId, code, message);
}

// 发布成功回调函数
void handlePublishSuccess(void *context, int messageId, int code, char *message)
{
    printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handlePublishSuccess() messageId %d\n", messageId);
}

// 发布失败回调函数
void handlePublishFailure(void *context, int messageId, int code, char *message)
{
    printfLog(EN_LOG_LEVEL_WARNING, "AgentLiteDemo: handlePublishFailure() warning, messageId %d, code %d, messsage %s\n", messageId, code, message);
}

//-------------------------------------------处理消息到达------------------------------------------------------------------------------

// 处理下行消息
void handleMessageDown(void *context, int messageId, int code, char *message)
{
    printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handleMessageDown(), messageId %d, code %d, messsage %s\n", messageId, code, message);

    JSON *root = JSON_Parse(message); // 将字符串转换为JSON

    char *content = JSON_GetStringFromObject(root, "content", "-1"); // 获取content的值
    printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handleMessageDown(), content %s\n", content);

    char *object_device_id = JSON_GetStringFromObject(root, "object_device_id", "-1"); // 获取object_device_id的值
    printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handleMessageDown(), object_device_id %s\n", object_device_id);

    char *name = JSON_GetStringFromObject(root, "name", "-1"); // 获取name的值
    printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handleMessageDown(), name %s\n", name);

    char *id = JSON_GetStringFromObject(root, "id", "-1"); // 获取id的值
    printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handleMessageDown(), id %s\n", id);

    JSON_Delete(root);
}

// 处理命令请求 - 华为云命令下发回调函数
void handleCommandRequest(void *context, int messageId, int code, char *message, char *requestId)
{
    // 打印命令接收基本信息：消息ID、状态码、请求ID
    printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handleCommandRequest(), messageId %d, code %d, requestId %s\n", messageId, code, requestId);
    // 打印原始命令消息用于调试
    printfLog(EN_LOG_LEVEL_DEBUG, "Raw message: %s\n", message);

    // 解析华为云下发的命令JSON消息
    JSON *root = JSON_Parse(message);

    // 从JSON中提取服务ID字段，用于标识命令所属的服务
    char *service_id = JSON_GetStringFromObject(root, "service_id", "-1");
    printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handleCommandRequest(), service_id %s\n", service_id);

    // 从JSON中提取命令名称，这是命令分发的关键字段
    char *command_name = JSON_GetStringFromObject(root, "command_name", "-1");
    printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handleCommandRequest(), command_name %s\n", command_name);

    // 从JSON中提取参数对象，包含命令的具体执行参数
    JSON *paras = JSON_GetObjectFromObject(root, "paras");
    printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handleCommandRequest(), paras found: %s\n", paras ? "YES" : "NO");

    // 定义命令参数变量，初始化为默认值
    char *action = NULL;    // 动作类型（如：on/off/blink等）
    char *target = NULL;    // 目标设备（如：led1/all等）
    char *data_type = NULL; // 数据类型（用于显示数据更新）
    int value = -1;         // 数值参数（如：亮度值、次数等）

    // 检查是否存在参数对象
    if (paras)
    {

        printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handleCommandRequest(), sleepTime %d\n", sleepTime);

        // 处理显示数据更新命令
        if (strcmp(command_name, "update_display_data") == 0)
        {
            // 提取数据类型（如：total_spaces, floor_b1_total等）
            data_type = JSON_GetStringFromObject(paras, "data_type", NULL);
            // 提取新的数值
            value = JSON_GetIntFromObject(paras, "new_value", -1);

            // 打印解析的参数信息
            printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: update_display_data - data_type: %s, new_value: %d\n",
                      data_type ? data_type : "NULL", value);
        }
        // 处理LED控制命令
        else if (strcmp(command_name, "led_control") == 0)
        {
            // 提取动作（on/off/blink）
            action = JSON_GetStringFromObject(paras, "action", NULL);
            // 提取目标LED（all/1/2/3/4）
            target = JSON_GetStringFromObject(paras, "target", NULL);
            // 提取数值参数（如：闪烁次数、LED编号）
            value = JSON_GetIntFromObject(paras, "value", -1);

            printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: led_control - action: %s, target: %s, value: %d\n",
                      action ? action : "NULL", target ? target : "NULL", value);
        }
        // 处理蜂鸣器控制命令
        else if (strcmp(command_name, "buzzer_control") == 0)
        {
            // 提取动作（on/off/alarm等）
            action = JSON_GetStringFromObject(paras, "action", NULL);
            // 提取数值参数（如：报警次数、持续时间）
            value = JSON_GetIntFromObject(paras, "value", -1);

            printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: buzzer_control - action: %s, value: %d\n",
                      action ? action : "NULL", value);
        }

        // 转发命令到开发板（使用华为云格式）
        // 将解析出的参数打包并发送到GEC6818开发板
        forward_command_to_gec6818(command_name, action, target, value, data_type, requestId);
    }
    else
    {
        // 命令中没有参数的情况处理
        printfLog(EN_LOG_LEVEL_WARNING, "AgentLiteDemo: No parameters found in command\n");
        // 即使没有参数也要转发命令（使用默认参数）
        forward_command_to_gec6818(command_name, NULL, NULL, -1, NULL, requestId);
    }

    // 立即回复命令接收成功 - 不等待设备执行完成
    // 这是异步处理模式：先确认接收，再异步执行
    Test_commandResponse(requestId);

    // 释放JSON解析占用的内存
    JSON_Delete(root);
}

// 处理属性设置
void handlePropertiesSet(void *context, int messageId, int code, char *message, char *requestId)
{
    printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handlePropertiesSet(), messageId %d, code %d, messsage %s, requestId %s\n", messageId, code, message, requestId);

    JSON *root = JSON_Parse(message); // 将字符串转换为JSON

    char *object_device_id = JSON_GetStringFromObject(root, "object_device_id", "-1"); // 获取object_device_id的值
    printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handlePropertiesSet(), object_device_id %s\n", object_device_id);

    JSON *services = JSON_GetObjectFromObject(root, "services"); // 获取services数组
    printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handlePropertiesSet(), services %s\n", services);

    int dataSize = JSON_GetArraySize(services); // 获取services数组长度
    printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handlePropertiesSet(), dataSize %d\n", dataSize);

    if (dataSize > 0)
    {
        JSON *service = JSON_GetObjectFromArray(services, 0); // 只获取第一个来演示
        printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handleSubDeviceMessageDown(), service %s\n", service);
        if (service)
        {
            char *service_id = JSON_GetStringFromObject(service, "service_id", NULL);

            printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handlePropertiesSet(), service_id %s\n", service_id);

            JSON *properties = JSON_GetObjectFromObject(service, "properties");

            alarmValue = JSON_GetIntFromObject(properties, "alarm", NULL);
            printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handlePropertiesSet(), alarmValue %d\n", alarmValue);
        }
    }

    Test_propSetResponse(requestId); // 命令响应

    JSON_Delete(root);
}

// 处理属性获取
void handlePropertiesGet(void *context, int messageId, int code, char *message, char *requestId)
{
    printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handlePropertiesGet(), messageId %d, code %d, messsage %s, requestId %s\n", messageId, code, message, requestId);

    JSON *root = JSON_Parse(message);

    char *object_device_id = JSON_GetStringFromObject(root, "object_device_id", "-1"); // 获取object_device_id的值
    printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handlePropertiesGet(), object_device_id %s\n", object_device_id);

    char *service_id = JSON_GetStringFromObject(root, "service_id", "-1"); // 获取service_id的值
    printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handlePropertiesGet(), service_id %s\n", service_id);

    Test_propGetResponse(requestId); // 命令响应

    JSON_Delete(root);
}

// 处理设备属性获取响应
void handleDeviceProGetResp(void *context, int messageId, int code, char *message, char *requestId)
{
    printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handleDeviceProGetResp(), messageId %d, code %d, messsage %s, requestId %s\n", messageId, code, message, requestId);
    // 开始通过主题 $oc/devices/{device_id}/sys/commands/response/request_id={request_id} 响应命令
}

// 处理事件下行
void handleEventsDown(void *context, int messageId, int code, char *message)
{
    printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handleSubDeviceMessageDown(), messageId %d, code %d, messsage %s\n", messageId, code, message);

    // 如何获取参数的演示
    JSON *root = JSON_Parse(message);

    char *object_device_id = JSON_GetStringFromObject(root, "object_device_id", "-1"); // 获取object_device_id的值
    printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handleEventsDown(), object_device_id %s\n", object_device_id);

    JSON *service = JSON_GetObjectFromObject(root, "services"); // 获取services对象
    printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handleEventsDown(), services %s\n", service);

    int dataSize = JSON_GetArraySize(service); // 获取services大小
    printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handleEventsDown(), dataSize %d\n", dataSize);

    if (dataSize > 0)
    {
        JSON *serviceEvent = JSON_GetObjectFromArray(service, 0); // 获取ServiceEvent对象
        printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handleEventsDown(), serviceEvent %s\n", serviceEvent);
        if (serviceEvent)
        {
            char *service_id = JSON_GetStringFromObject(serviceEvent, "service_id", NULL); // 获取service_id的值
            printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handleEventsDown(), service_id %s\n", service_id);

            char *event_type = NULL;                                                 // 判断是添加还是删除子设备
            event_type = JSON_GetStringFromObject(serviceEvent, "event_type", NULL); // 获取event_type的值
            printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handleEventsDown(), event_type %s\n", event_type);

            char *event_time = JSON_GetStringFromObject(serviceEvent, "event_time", NULL); // 获取event_time的值
            printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handleEventsDown(), event_time %s\n", event_time);

            JSON *paras = JSON_GetObjectFromObject(serviceEvent, "paras"); // 获取paras对象
            printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handleEventsDown(), paras %s\n", paras);

            JSON *devices = JSON_GetObjectFromObject(paras, "devices"); // 获取devices对象
            printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handleEventsDown(), devices %s\n", devices);

            int version = JSON_GetIntFromObject(paras, "version", -1); // 获取version的值
            printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handleEventsDown(), version %d\n", version);

            int devicesSize = JSON_GetArraySize(devices); // 获取devicesSize大小
            printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handleEventsDown(), devicesSize %d\n", devicesSize);

            if (devicesSize > 0)
            {
                JSON *deviceInfo = JSON_GetObjectFromArray(devices, 0); // 获取deviceInfo对象
                printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handleEventsDown(), deviceInfo %s\n", deviceInfo);

                char *parent_device_id = JSON_GetStringFromObject(serviceEvent, "parent_device_id", NULL); // 获取parent_device_id的值
                printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handleEventsDown(), parent_device_id %s\n", parent_device_id);

                char *node_id = JSON_GetStringFromObject(serviceEvent, "node_id", NULL); // 获取node_id的值
                printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handleEventsDown(), node_id %s\n", node_id);

                subDeviceId = JSON_GetStringFromObject(serviceEvent, "device_id", NULL); // 获取device_id的值
                printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handleEventsDown(), device_id %s\n", subDeviceId);

                if (!strcmp(event_type, "add_sub_device_notify")) // 添加子设备
                {
                    char *name = JSON_GetStringFromObject(serviceEvent, "name", NULL); // 获取name的值
                    printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handleEventsDown(), name %s\n", name);

                    char *description = JSON_GetStringFromObject(serviceEvent, "description", NULL); // 获取description的值
                    printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handleEventsDown(), description %s\n", description);

                    char *manufacturer_id = JSON_GetStringFromObject(serviceEvent, "manufacturer_id", NULL); // 获取manufacturer_id的值
                    printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handleEventsDown(), manufacturer_id %s\n", manufacturer_id);

                    char *model = JSON_GetStringFromObject(serviceEvent, "model", NULL); // 获取model的值
                    printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handleEventsDown(), model %s\n", model);

                    char *product_id = JSON_GetStringFromObject(serviceEvent, "product_id", NULL); // 获取product_id的值
                    printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handleEventsDown(), product_id %s\n", product_id);

                    char *fw_version = JSON_GetStringFromObject(serviceEvent, "fw_version", NULL); // 获取fw_version的值
                    printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handleEventsDown(), fw_version %s\n", fw_version);

                    char *sw_version = JSON_GetStringFromObject(serviceEvent, "sw_version", NULL); // 获取sw_version的值
                    printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handleEventsDown(), sw_version %s\n", sw_version);

                    char *status = JSON_GetStringFromObject(serviceEvent, "status", NULL); // 获取status的值
                    printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handleEventsDown(), status %s\n", status);

                    Test_batchPropertiesReport(); // 命令响应
                }
                else if (!strcmp(event_type, "delete_sub_device_notify")) // 删除子设备
                {
                    printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handleEventsDown(), delete a sub device.\n");
                }
                else
                {
                    printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: handleEventsDown(), default.\n");
                }
            }
        }
    }

    JSON_Delete(root);
}

// 设置连接配置
void setConnectConfig()
{
    FILE *file;
    long length;
    char *content;
    cJSON *json;

    // 读取配置文件
    file = fopen("./ClientConf.json", "rb");
    fseek(file, 0, SEEK_END);
    length = ftell(file);
    fseek(file, 0, SEEK_SET);
    content = (char *)malloc(length + 1);
    fread(content, 1, length, file);
    fclose(file);

    json = cJSON_Parse(content);

    // 从配置文件中读取设备ID和密钥
    username_ = JSON_GetStringFromObject(json, "deviceId", NULL);
    password_ = JSON_GetStringFromObject(json, "secret", NULL);
    char *url = JSON_GetStringFromObject(json, "serverUri", NULL);

    // 处理URL，移除ssl://和端口号
    deleteSubStr(url, "ssl://");
    deleteSubStr(url, ":8883");

    serverIp_ = url;
}

//----------------------------------------------------------------------------------------------------------------------------------------------

// 设置认证配置
void setAuthConfig()
{
    // 设置MQTT地址
    IOTA_ConfigSetStr(EN_IOTA_CFG_MQTT_ADDR, serverIp_);
    // 设置MQTT端口
    IOTA_ConfigSetUint(EN_IOTA_CFG_MQTT_PORT, port_);
    // 设置设备ID
    IOTA_ConfigSetStr(EN_IOTA_CFG_DEVICEID, username_);
    // 设置设备密钥
    IOTA_ConfigSetStr(EN_IOTA_CFG_DEVICESECRET, password_);

#ifdef _SYS_LOG
    // 设置系统日志
    IOTA_ConfigSetUint(EN_IOTA_CFG_LOG_LOCAL_NUMBER, LOG_LOCAL7);
    IOTA_ConfigSetUint(EN_IOTA_CFG_LOG_LEVEL, LOG_INFO);
#endif
}

// 设置回调函数
void setMyCallbacks()
{
    // 设置连接成功回调
    IOTA_SetCallback(EN_IOTA_CALLBACK_CONNECT_SUCCESS, handleAuthSuccess);
    // 设置连接失败回调
    IOTA_SetCallback(EN_IOTA_CALLBACK_CONNECT_FAILURE, handleAuthFailure);
    // 设置连接丢失回调
    IOTA_SetCallback(EN_IOTA_CALLBACK_CONNECTION_LOST, handleConnectionLost);

    // 设置断开连接成功回调
    IOTA_SetCallback(EN_IOTA_CALLBACK_DISCONNECT_SUCCESS, handleDisAuthSuccess);
    // 设置断开连接失败回调
    IOTA_SetCallback(EN_IOTA_CALLBACK_DISCONNECT_FAILURE, handleDisAuthFailure);

    // 设置订阅成功回调
    IOTA_SetCallback(EN_IOTA_CALLBACK_SUBSCRIBE_SUCCESS, handleSubscribesuccess);
    // 设置订阅失败回调
    IOTA_SetCallback(EN_IOTA_CALLBACK_SUBSCRIBE_FAILURE, handleSubscribeFailure);

    // 设置发布成功回调
    IOTA_SetCallback(EN_IOTA_CALLBACK_PUBLISH_SUCCESS, handlePublishSuccess);
    // 设置发布失败回调
    IOTA_SetCallback(EN_IOTA_CALLBACK_PUBLISH_FAILURE, handlePublishFailure);

    // 设置消息下行回调
    IOTA_SetCallback(EN_IOTA_CALLBACK_MESSAGE_DOWN, handleMessageDown);
    // 设置命令请求回调（带主题）
    IOTA_SetCallbackWithTopic(EN_IOTA_CALLBACK_COMMAND_REQUEST, handleCommandRequest);
    // 设置属性设置回调（带主题）
    IOTA_SetCallbackWithTopic(EN_IOTA_CALLBACK_PROPERTIES_SET, handlePropertiesSet);
    // 设置属性获取回调（带主题）
    IOTA_SetCallbackWithTopic(EN_IOTA_CALLBACK_PROPERTIES_GET, handlePropertiesGet);
    // 设置子设备消息下行回调
    IOTA_SetCallback(EN_IOTA_CALLBACK_SUB_DEVICE_MESSAGE_DOWN, handleEventsDown);
}

// 自定义日志打印函数
void myPrintLog(int level, char *format, va_list args)
{
    vprintf(format, args); // 将日志打印到控制台
    /* 如果想在系统日志文件中打印日志，可以这样做：
     * vsyslog(level, format, args);
     */
}

// TCP服务器线程函数
void *tcp_server_thread_func(void *arg)
{
    struct sockaddr_in server_addr, client_addr;
    socklen_t client_len = sizeof(client_addr);

    // 创建TCP套接字
    tcp_server_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (tcp_server_fd < 0)
    {
        printfLog(EN_LOG_LEVEL_ERROR, "TCP server socket creation failed\n");
        return NULL;
    }

    // 设置端口复用
    int opt = 1;
    setsockopt(tcp_server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));

    // 绑定地址
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY;
    server_addr.sin_port = htons(TCP_SERVER_PORT);

    if (bind(tcp_server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
    {
        printfLog(EN_LOG_LEVEL_ERROR, "TCP server bind failed\n");
        close(tcp_server_fd);
        return NULL;
    }

    // 开始监听
    if (listen(tcp_server_fd, 5) < 0)
    {
        printfLog(EN_LOG_LEVEL_ERROR, "TCP server listen failed\n");
        close(tcp_server_fd);
        return NULL;
    }

    printfLog(EN_LOG_LEVEL_INFO, "TCP Server started on port %d, waiting for GEC6818 connections...\n", TCP_SERVER_PORT);

    while (tcp_running)
    {
        // 接受客户端连接
        int client_fd = accept(tcp_server_fd, (struct sockaddr *)&client_addr, &client_len);
        if (client_fd < 0)
        {
            if (tcp_running)
            {
                printfLog(EN_LOG_LEVEL_ERROR, "TCP server accept failed\n");
            }
            continue;
        }

        printfLog(EN_LOG_LEVEL_INFO, "New connection from GEC6818: %s:%d\n",
                  inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));

        // 保存客户端连接用于命令下发
        set_client_connection(client_fd);

        // 处理客户端连接
        char buffer[BUFFER_SIZE];
        ssize_t bytes_read;

        while ((bytes_read = recv(client_fd, buffer, BUFFER_SIZE - 1, 0)) > 0)
        {
            buffer[bytes_read] = '\0';
            printfLog(EN_LOG_LEVEL_INFO, "Received data chunk: %d bytes\n", bytes_read);

            // 处理数据（包含拼接逻辑）
            process_parking_data(buffer, bytes_read);

            // 回复确认
            char ack_msg[256];
            snprintf(ack_msg, sizeof(ack_msg), "{\"status\":\"success\",\"message\":\"Data received\"}");
            send(client_fd, ack_msg, strlen(ack_msg), 0);
        }

        // 连接断开
        close(client_fd);
        set_client_connection(-1); // 清除客户端连接
        printfLog(EN_LOG_LEVEL_INFO, "GEC6818 disconnected\n");
    }

    close(tcp_server_fd);
    return NULL;
}

// 华为云数据上报函数 - 停车场专用版本（单服务）
void report_to_huaweicloud(const char *parking_data)
{
    // 开始华为云上报流程的日志标记
    printfLog(EN_LOG_LEVEL_INFO, "=== Huawei Cloud Report ===\n");

    // 解析接收到的停车场数据JSON字符串为cJSON对象
    cJSON *root = cJSON_Parse(parking_data);
    // 检查JSON解析是否成功
    if (!root)
    {
        printfLog(EN_LOG_LEVEL_ERROR, "Failed to parse parking data JSON\n");
        return; // 解析失败则直接返回
    }

    // 定义华为云服务数据结构 - 使用单个服务
    int serviceNum = 1;
    ST_IOTA_SERVICE_DATA_INFO services[serviceNum];
    // 创建新的JSON对象用于存储属性数据
    cJSON *properties = cJSON_CreateObject();

    // 1. 基础停车数据 - 从原始JSON中提取基础停车相关字段
    cJSON *total_spaces = cJSON_GetObjectItem(root, "total_spaces");         // 总车位数
    cJSON *available_spaces = cJSON_GetObjectItem(root, "available_spaces"); // 可用车位数
    cJSON *occupied_spaces = cJSON_GetObjectItem(root, "occupied_spaces");   // 已占用车位数
    cJSON *utilization_rate = cJSON_GetObjectItem(root, "utilization_rate"); // 车位利用率
    cJSON *vehicles_in = cJSON_GetObjectItem(root, "vehicles_in");           // 今日进场车辆数
    cJSON *vehicles_out = cJSON_GetObjectItem(root, "vehicles_out");         // 今日出场车辆数
    cJSON *vehicles_current = cJSON_GetObjectItem(root, "vehicles_current"); // 当前在场车辆数
    cJSON *peak_hour_flag = cJSON_GetObjectItem(root, "peak_hour_flag");     // 高峰时段标志

    // 将解析的基础停车数据添加到属性对象中（如果字段存在）
    if (total_spaces)
        cJSON_AddNumberToObject(properties, "total_spaces", total_spaces->valuedouble);
    if (available_spaces)
        cJSON_AddNumberToObject(properties, "available_spaces", available_spaces->valuedouble);
    if (occupied_spaces)
        cJSON_AddNumberToObject(properties, "occupied_spaces", occupied_spaces->valuedouble);
    if (utilization_rate)
        cJSON_AddNumberToObject(properties, "utilization_rate", utilization_rate->valuedouble);
    if (vehicles_in)
        cJSON_AddNumberToObject(properties, "vehicles_in", vehicles_in->valuedouble);
    if (vehicles_out)
        cJSON_AddNumberToObject(properties, "vehicles_out", vehicles_out->valuedouble);
    if (vehicles_current)
        cJSON_AddNumberToObject(properties, "vehicles_current", vehicles_current->valuedouble);
    if (peak_hour_flag)
        cJSON_AddNumberToObject(properties, "peak_hour_flag", peak_hour_flag->valuedouble);

    // 2. 环境数据 - 提取环境监测相关字段
    cJSON *temperature = cJSON_GetObjectItem(root, "temperature"); // 温度
    cJSON *humidity = cJSON_GetObjectItem(root, "humidity");       // 湿度
    cJSON *light_level = cJSON_GetObjectItem(root, "light_level"); // 光照强度
    cJSON *air_quality = cJSON_GetObjectItem(root, "air_quality"); // 空气质量

    // 将环境数据添加到属性对象
    if (temperature)
        cJSON_AddNumberToObject(properties, "temperature", temperature->valuedouble);
    if (humidity)
        cJSON_AddNumberToObject(properties, "humidity", humidity->valuedouble);
    if (light_level)
        cJSON_AddNumberToObject(properties, "light_level", light_level->valuedouble);
    if (air_quality)
        cJSON_AddNumberToObject(properties, "air_quality", air_quality->valuedouble);

    // 3. 楼层数据 - 提取各楼层停车数据
    cJSON *floor_b1_total = cJSON_GetObjectItem(root, "floor_b1_total");             // 地下1层总车位
    cJSON *floor_b1_available = cJSON_GetObjectItem(root, "floor_b1_available");     // 地下1层可用车位
    cJSON *floor_b1_utilization = cJSON_GetObjectItem(root, "floor_b1_utilization"); // 地下1层利用率
    cJSON *floor_b2_total = cJSON_GetObjectItem(root, "floor_b2_total");             // 地下2层总车位
    cJSON *floor_b2_available = cJSON_GetObjectItem(root, "floor_b2_available");     // 地下2层可用车位
    cJSON *floor_b2_utilization = cJSON_GetObjectItem(root, "floor_b2_utilization"); // 地下2层利用率
    cJSON *floor_b3_total = cJSON_GetObjectItem(root, "floor_b3_total");             // 地下3层总车位
    cJSON *floor_b3_available = cJSON_GetObjectItem(root, "floor_b3_available");     // 地下3层可用车位
    cJSON *floor_b3_utilization = cJSON_GetObjectItem(root, "floor_b3_utilization"); // 地下3层利用率

    // 将楼层数据添加到属性对象
    if (floor_b1_total)
        cJSON_AddNumberToObject(properties, "floor_b1_total", floor_b1_total->valuedouble);
    if (floor_b1_available)
        cJSON_AddNumberToObject(properties, "floor_b1_available", floor_b1_available->valuedouble);
    if (floor_b1_utilization)
        cJSON_AddNumberToObject(properties, "floor_b1_utilization", floor_b1_utilization->valuedouble);
    if (floor_b2_total)
        cJSON_AddNumberToObject(properties, "floor_b2_total", floor_b2_total->valuedouble);
    if (floor_b2_available)
        cJSON_AddNumberToObject(properties, "floor_b2_available", floor_b2_available->valuedouble);
    if (floor_b2_utilization)
        cJSON_AddNumberToObject(properties, "floor_b2_utilization", floor_b2_utilization->valuedouble);
    if (floor_b3_total)
        cJSON_AddNumberToObject(properties, "floor_b3_total", floor_b3_total->valuedouble);
    if (floor_b3_available)
        cJSON_AddNumberToObject(properties, "floor_b3_available", floor_b3_available->valuedouble);
    if (floor_b3_utilization)
        cJSON_AddNumberToObject(properties, "floor_b3_utilization", floor_b3_utilization->valuedouble);

    // 4. 客户行为分析 - 特别注意：需要转换x100字段为浮点数
    cJSON *avg_parking_time_x100 = cJSON_GetObjectItem(root, "avg_parking_time_x100"); // 平均停车时间（×100）
    cJSON *avg_consumption_x100 = cJSON_GetObjectItem(root, "avg_consumption_x100");   // 平均消费金额（×100）
    cJSON *member_ratio = cJSON_GetObjectItem(root, "member_ratio");                   // 会员比例

    // 处理乘以100的字段：除以100转换为实际值
    if (avg_parking_time_x100)
    {
        double avg_parking_time = avg_parking_time_x100->valuedouble / 100.0; // 转换为实际小时数
        cJSON_AddNumberToObject(properties, "avg_parking_time", avg_parking_time);
        // 记录转换过程用于调试
        printfLog(EN_LOG_LEVEL_DEBUG, "Converted avg_parking_time: %d -> %.2f\n",
                  (int)avg_parking_time_x100->valuedouble, avg_parking_time);
    }

    if (avg_consumption_x100)
    {
        double avg_consumption = avg_consumption_x100->valuedouble / 100.0; // 转换为实际金额
        cJSON_AddNumberToObject(properties, "avg_consumption", avg_consumption);
        printfLog(EN_LOG_LEVEL_DEBUG, "Converted avg_consumption: %d -> %.2f\n",
                  (int)avg_consumption_x100->valuedouble, avg_consumption);
    }

    if (member_ratio)
        cJSON_AddNumberToObject(properties, "member_ratio", member_ratio->valuedouble);

    // 5. 停车时长分布 - 提取不同停车时长的车辆比例
    cJSON *parking_time_less_1h = cJSON_GetObjectItem(root, "parking_time_less_1h"); // 停车<1小时比例
    cJSON *parking_time_1_2h = cJSON_GetObjectItem(root, "parking_time_1_2h");       // 停车1-2小时比例
    cJSON *parking_time_2_4h = cJSON_GetObjectItem(root, "parking_time_2_4h");       // 停车2-4小时比例
    cJSON *parking_time_more_4h = cJSON_GetObjectItem(root, "parking_time_more_4h"); // 停车>4小时比例

    // 将停车时长分布数据添加到属性对象
    if (parking_time_less_1h)
        cJSON_AddNumberToObject(properties, "parking_time_less_1h", parking_time_less_1h->valuedouble);
    if (parking_time_1_2h)
        cJSON_AddNumberToObject(properties, "parking_time_1_2h", parking_time_1_2h->valuedouble);
    if (parking_time_2_4h)
        cJSON_AddNumberToObject(properties, "parking_time_2_4h", parking_time_2_4h->valuedouble);
    if (parking_time_more_4h)
        cJSON_AddNumberToObject(properties, "parking_time_more_4h", parking_time_more_4h->valuedouble);

    // 6. 车牌识别数据 - 提取车牌识别相关统计信息
    cJSON *recognized_vehicles = cJSON_GetObjectItem(root, "recognized_vehicles");       // 已识别车辆数
    cJSON *unrecognized_rate_x100 = cJSON_GetObjectItem(root, "unrecognized_rate_x100"); // 未识别率（×100）
    cJSON *vehicle_type_truck = cJSON_GetObjectItem(root, "vehicle_type_truck");         // 货车数量
    cJSON *vehicle_type_suv = cJSON_GetObjectItem(root, "vehicle_type_suv");             // SUV数量
    cJSON *vehicle_type_car = cJSON_GetObjectItem(root, "vehicle_type_car");             // 轿车数量

    if (recognized_vehicles)
        cJSON_AddNumberToObject(properties, "recognized_vehicles", recognized_vehicles->valuedouble);

    // 处理未识别率：除以100转换为百分比
    if (unrecognized_rate_x100)
    {
        double unrecognized_rate = unrecognized_rate_x100->valuedouble / 100.0; // 转换为实际百分比
        cJSON_AddNumberToObject(properties, "unrecognized_rate", unrecognized_rate);
        printfLog(EN_LOG_LEVEL_DEBUG, "Converted unrecognized_rate: %d -> %.2f\n",
                  (int)unrecognized_rate_x100->valuedouble, unrecognized_rate);
    }

    // 添加车辆类型数据
    if (vehicle_type_truck)
        cJSON_AddNumberToObject(properties, "vehicle_type_truck", vehicle_type_truck->valuedouble);
    if (vehicle_type_suv)
        cJSON_AddNumberToObject(properties, "vehicle_type_suv", vehicle_type_suv->valuedouble);
    if (vehicle_type_car)
        cJSON_AddNumberToObject(properties, "vehicle_type_car", vehicle_type_car->valuedouble);

    // 7. 客户反馈数据 - 特别注意：字符串字段需要特殊处理
    cJSON *common_feedback = cJSON_GetObjectItem(root, "common_feedback");             // 常见反馈内容（字符串）
    cJSON *avg_waiting_time_x100 = cJSON_GetObjectItem(root, "avg_waiting_time_x100"); // 平均等待时间（×100）
    cJSON *facility_score_x100 = cJSON_GetObjectItem(root, "facility_score_x100");     // 设施评分（×100）
    cJSON *service_score_x100 = cJSON_GetObjectItem(root, "service_score_x100");       // 服务评分（×100）
    cJSON *satisfaction_score = cJSON_GetObjectItem(root, "satisfaction_score");       // 满意度评分

    // 处理中文字符串 - 需要确保编码正确
    if (common_feedback && cJSON_IsString(common_feedback))
    {
        // 直接使用原始字符串（假设编码正确）
        cJSON_AddStringToObject(properties, "common_feedback", common_feedback->valuestring);
        printfLog(EN_LOG_LEVEL_DEBUG, "common_feedback string: %s\n", common_feedback->valuestring);
    }
    else
    {
        // 如果解析有问题，使用固定默认值
        cJSON_AddStringToObject(properties, "common_feedback", "车位充足");
        printfLog(EN_LOG_LEVEL_WARNING, "common_feedback not found or not string, using default\n");
    }

    // 处理等待时间：除以100转换为实际分钟数
    if (avg_waiting_time_x100)
    {
        double avg_waiting_time = avg_waiting_time_x100->valuedouble / 100.0;
        cJSON_AddNumberToObject(properties, "avg_waiting_time", avg_waiting_time);
        printfLog(EN_LOG_LEVEL_DEBUG, "Converted avg_waiting_time: %d -> %.2f\n",
                  (int)avg_waiting_time_x100->valuedouble, avg_waiting_time);
    }

    // 处理设施评分：除以100转换为5分制
    if (facility_score_x100)
    {
        double facility_score = facility_score_x100->valuedouble / 100.0;
        cJSON_AddNumberToObject(properties, "facility_score", facility_score);
        printfLog(EN_LOG_LEVEL_DEBUG, "Converted facility_score: %d -> %.2f\n",
                  (int)facility_score_x100->valuedouble, facility_score);
    }

    // 处理服务评分：除以100转换为5分制
    if (service_score_x100)
    {
        double service_score = service_score_x100->valuedouble / 100.0;
        cJSON_AddNumberToObject(properties, "service_score", service_score);
        printfLog(EN_LOG_LEVEL_DEBUG, "Converted service_score: %d -> %.2f\n",
                  (int)service_score_x100->valuedouble, service_score);
    }

    if (satisfaction_score)
        cJSON_AddNumberToObject(properties, "satisfaction_score", satisfaction_score->valuedouble);

    // 8. 高峰时段数据 - 提取各时段车流量统计
    cJSON *hour_6_count = cJSON_GetObjectItem(root, "hour_6_count");   // 6点车流量
    cJSON *hour_8_count = cJSON_GetObjectItem(root, "hour_8_count");   // 8点车流量
    cJSON *hour_10_count = cJSON_GetObjectItem(root, "hour_10_count"); // 10点车流量
    cJSON *hour_12_count = cJSON_GetObjectItem(root, "hour_12_count"); // 12点车流量
    cJSON *hour_14_count = cJSON_GetObjectItem(root, "hour_14_count"); // 14点车流量
    cJSON *hour_16_count = cJSON_GetObjectItem(root, "hour_16_count"); // 16点车流量
    cJSON *hour_18_count = cJSON_GetObjectItem(root, "hour_18_count"); // 18点车流量
    cJSON *hour_20_count = cJSON_GetObjectItem(root, "hour_20_count"); // 20点车流量

    // 将高峰时段数据添加到属性对象
    if (hour_6_count)
        cJSON_AddNumberToObject(properties, "hour_6_count", hour_6_count->valuedouble);
    if (hour_8_count)
        cJSON_AddNumberToObject(properties, "hour_8_count", hour_8_count->valuedouble);
    if (hour_10_count)
        cJSON_AddNumberToObject(properties, "hour_10_count", hour_10_count->valuedouble);
    if (hour_12_count)
        cJSON_AddNumberToObject(properties, "hour_12_count", hour_12_count->valuedouble);
    if (hour_14_count)
        cJSON_AddNumberToObject(properties, "hour_14_count", hour_14_count->valuedouble);
    if (hour_16_count)
        cJSON_AddNumberToObject(properties, "hour_16_count", hour_16_count->valuedouble);
    if (hour_18_count)
        cJSON_AddNumberToObject(properties, "hour_18_count", hour_18_count->valuedouble);
    if (hour_20_count)
        cJSON_AddNumberToObject(properties, "hour_20_count", hour_20_count->valuedouble);

    // 添加当前时间戳作为上报时间
    cJSON_AddNumberToObject(properties, "report_time", time(NULL));

    // 将属性JSON对象转换为字符串格式，用于华为云上报
    char *properties_str = cJSON_PrintUnformatted(properties);
    printfLog(EN_LOG_LEVEL_INFO, "Properties to report: %s\n", properties_str);

    // 设置华为云服务数据结构
    services[0].event_time = getEventTimeStamp(); // 获取事件时间戳
    services[0].service_id = "ParkingManagement"; // 服务ID（对应华为云物模型）
    services[0].properties = properties_str;      // 属性数据字符串

    // 调用华为云SDK进行属性上报
    int messageId = IOTA_PropertiesReport(services, serviceNum);
    // 检查上报结果
    if (messageId != 0)
    {
        printfLog(EN_LOG_LEVEL_ERROR, "Failed to report to Huawei Cloud, messageId: %d\n", messageId);
    }
    else
    {
        printfLog(EN_LOG_LEVEL_INFO, "Successfully reported data to Huawei Cloud\n");
    }

    // 清理资源：释放所有分配的JSON对象和字符串
    cJSON_Delete(properties); // 释放属性JSON对象
    cJSON_Delete(root);       // 释放原始数据JSON对象
    free(properties_str);     // 释放属性字符串内存
}

// 修改数据处理逻辑，添加完整的数据拼接
void process_parking_data(const char *data_chunk, size_t chunk_len)
{
    // 检查缓冲区是否足够 - 防止缓冲区溢出
    // 如果当前缓冲区长度加上新数据长度超过缓冲区总大小，则重置缓冲区
    if (g_parking_buffer_len + chunk_len >= sizeof(g_parking_buffer))
    {
        printfLog(EN_LOG_LEVEL_ERROR, "Parking buffer overflow, resetting\n");
        g_parking_buffer_len = 0; // 重置缓冲区长度，丢弃旧数据
    }

    // 追加数据到缓冲区 - 核心拼接逻辑
    // 将新接收的数据块复制到缓冲区的末尾位置
    memcpy(g_parking_buffer + g_parking_buffer_len, data_chunk, chunk_len);
    // 更新缓冲区长度，记录当前总数据量
    g_parking_buffer_len += chunk_len;
    // 在缓冲区末尾添加字符串结束符，便于字符串操作
    g_parking_buffer[g_parking_buffer_len] = '\0';

    // 调试信息：打印当前缓冲区内容和长度
    printfLog(EN_LOG_LEVEL_DEBUG, "Current buffer content (%zu bytes): %s\n", g_parking_buffer_len, g_parking_buffer);

    // 检查是否收到完整JSON（以"status":"normal"}"结尾）
    // 这是判断JSON数据完整的简单标记方法
    if (strstr(g_parking_buffer, "\"status\":\"normal\"}") != NULL)
    {
        // 找到完整JSON结束标记，说明收到了完整的数据包
        printfLog(EN_LOG_LEVEL_INFO, "Complete JSON data received, length: %zu\n", g_parking_buffer_len);

        // 调用华为云上报函数，将拼接完整的JSON数据发送到华为云
        report_to_huaweicloud(g_parking_buffer);

        // 清空缓冲区，准备接收下一个数据包
        g_parking_buffer_len = 0;
    }
    else
    {
        // 未找到完整结束标记，说明数据包还未接收完整
        // 继续等待后续数据块的到来
        printfLog(EN_LOG_LEVEL_INFO, "Waiting for more data, current length: %zu\n", g_parking_buffer_len);
    }
}

// 主函数
int main(int argc, char **argv)
{
#if defined(_DEBUG)
    setvbuf(stdout, NULL, _IONBF, 0); // 在调试模式下使控制台日志立即打印
#endif

    // 初始化停车场数据缓冲区
    g_parking_buffer_len = 0;
    memset(g_parking_buffer, 0, sizeof(g_parking_buffer));

    // 设置自定义日志打印回调
    IOTA_SetPrintLogCallback(myPrintLog);

    // 设置连接配置
    setConnectConfig();

    printfLog(EN_LOG_LEVEL_INFO, "AgentLiteDemo: start test ===================>\n");

    // 初始化华为云IoT
    if (IOTA_Init(workPath) > 0)
    {
        printfLog(EN_LOG_LEVEL_ERROR, "AgentLiteDemo: IOTA_Init() error, init failed\n");
        return 1;
    }

    // 设置认证配置和回调函数
    setAuthConfig();
    setMyCallbacks();

    // 连接华为云
    int ret = IOTA_Connect();
    if (ret != 0)
    {
        printfLog(EN_LOG_LEVEL_ERROR, "AgentLiteDemo: IOTA_Auth() error, Auth failed, result %d\n", ret);
    }
    else
    {
        printfLog(EN_LOG_LEVEL_INFO, "Successfully connected to Huawei Cloud\n");
    }

    timeSleep(1500);

    // 启动TCP服务器线程
    if (pthread_create(&tcp_server_thread, NULL, tcp_server_thread_func, NULL) != 0)
    {
        printfLog(EN_LOG_LEVEL_ERROR, "Failed to create TCP server thread\n");
    }
    else
    {
        printfLog(EN_LOG_LEVEL_INFO, "TCP server thread started successfully\n");
    }

    timeSleep(2000); // 等待2秒确保连接稳定

    int count = 0;
    while (count < 10000)
    {
        // 这里可以添加各种测试功能
        // Test_messageReport();       // 消息上报测试
        // Test_propertiesReport();    // 属性上报测试
        // Test_batchPropertiesReport(); // 批量属性上报测试
        // Test_commandResponse("1005"); // 命令响应测试
        // Test_propSetResponse("1006"); // 属性设置响应测试
        // Test_propGetResponse("1007"); // 属性获取响应测试

        timeSleep(sleepTime);
        count++;
    }

    // 等待TCP服务器线程
    tcp_running = 0;
    if (tcp_server_fd >= 0)
    {
        close(tcp_server_fd);
    }
    pthread_join(tcp_server_thread, NULL);

    return 0;
}